package tr.edu.ege.seagent.hobnobwebapp;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

import tr.edu.ege.seagent.hobnobontology.instance.HobNobResultSetSolution;
import tr.edu.ege.seagent.hobnobontology.instance.HobNobSPARQLQueries;

/**
 * Servlet implementation class HobNobAndroidServlet
 */
@WebServlet("/HobNobAndroidServlet")
public class HobNobAndroidServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public HobNobAndroidServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("application/json");

		PrintWriter out = response.getWriter();
		HobNobSPARQLQueries query = new HobNobSPARQLQueries();
		// getting all notification resources over http...
		List<HobNobResultSetSolution> notifications = query
				.findAllNotificationsOverHttp();

		Place place = new Place();
		place.setNotifications((ArrayList<String>) getNotifications(notifications));
		// writes result as a json object.
		out.println(new Gson().toJson(place).toString());

	}

	/**
	 * Gets notifications from the query result solution and returns
	 * notifications list.
	 * 
	 * @param resultSet
	 *            {@link HobNobSPARQLQueries#findAllNotificationsOverHttp()}
	 *            query results
	 * @return notification list which notifications is gotten from resultSet
	 */
	private List<String> getNotifications(
			List<HobNobResultSetSolution> resultSet) {
		List<String> notifications = new ArrayList<String>();
		for (HobNobResultSetSolution result : resultSet) {
			String notificationURI = result.getNotification().asResource()
					.getURI();
			if (!notifications.contains(notificationURI)) {
				notifications.add(notificationURI);
			}
		}
		return notifications;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
